import axios from 'axios'
import store from '@/store'

import customHistory from './history'
import { Toast } from 'antd-mobile'
import { clearToken, isAuth, setToken } from './auth'

// 创建axios实例
const http = axios.create({
  baseURL: 'http://toutiao.itheima.net/v1_0',
})

// 请求拦截器
http.interceptors.request.use((config) => {
  // 获取token
  const {
    login: { token },
  } = store.getState()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config
})

// 简化后台返回数据
http.interceptors.response.use(
  (res) => {
    return res.data
  },
  async (error) => {
    if (error.response.status === 401) {
      // Toast.show({
      //   content: error.response.data.message,
      //   icon: 'fail',
      //   afterClose: () => {
      //     // store.dispatch(logoutAction())
      //     customHistory.replace({
      //       pathname: '/login',
      //       state: {
      //         from: customHistory.location.pathname,
      //       },
      //     })
      //   },
      // })
      try {
        // 没有登录
        if (!isAuth) {
          throw Error(error)
        }
        // 登录过
        const { refresh_token } = store.getState().login
        const { data } = await axios.put(
          'http://toutiao.itheima.net/v1_0/authorizations',
          null,
          {
            headers: {
              Authorization: `Bearer ${refresh_token}`,
            },
          }
        )
        // 重新获取到token存储到本地和redux中
        const newTokens = {
          token: data.data.token,
          refresh_token,
        }
        setToken(newTokens)
        store.dispatch({ type: 'login/token', payload: newTokens })
        return http(error.config)
      } catch (error) {
        store.dispatch({ type: 'login/logout' })
        clearToken()
        Toast.show({
          content: '登录超时，请重新登录',
          icon: 'fail',
          afterClose: () => {
            customHistory.replace({
              pathname: '/login',
              state: { from: customHistory.location.pathname },
            })
          },
        })
        return Promise.reject(error)
      }
    }
    return Promise.reject(error)
  }
)

export default http
